package com.web.servlet;

import com.alibaba.fastjson2.JSON;
import com.web.JDBCUtils;
import com.web.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lenovo
 * @Description
 * @Date2025-2-27 21:29
 */


@WebServlet("/insertStudent")
public class InsertStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型为JSON
        resp.setContentType("application/json;charset=utf-8");

        // 从请求参数中获取学生信息
        String name = req.getParameter("name");
        String ageStr = req.getParameter("age");
        String gender = req.getParameter("gender");

        // 检查参数是否为空
        if (name == null || name.trim().isEmpty() ||
                ageStr == null || ageStr.trim().isEmpty() ||
                gender == null || gender.trim().isEmpty()) {
            // 如果参数为空，返回错误信息
            resp.getWriter().write(JSON.toJSONString("error: All fields are required"));
            return;
        }

        // 将年龄转换为整数
        int age;
        try {
            age = Integer.parseInt(ageStr);
        } catch (NumberFormatException e) {
            resp.getWriter().write(JSON.toJSONString("error: Invalid age"));
            return;
        }

        // 创建学生对象
        Student student = new Student();
        student.setName(name);
        student.setAge(age);
        student.setGender(gender);

        String sql = "INSERT INTO student_s (name, age, gender) VALUES (?, ?, ?)";

        Object[] params = new Object[]{student.getName(), student.getAge(), student.getGender()};

        try {
            int rowsAffected = JDBCUtils.update(sql, params);
            if (rowsAffected > 0) {
                // 如果插入成功，返回成功信息
                resp.getWriter().write(JSON.toJSONString("success: Student inserted successfully"));
            } else {
                // 如果插入失败，返回错误信息
                resp.getWriter().write(JSON.toJSONString("error: Failed to insert student"));
            }
        } catch (Exception e) {
            resp.getWriter().write(JSON.toJSONString("error: " + e.getMessage()));
        }
    }
}